﻿using System.Linq;
using Styx;
using Styx.CommonBot;
using Styx.CommonBot.POI;
using Styx.WoWInternals;
using Styx.WoWInternals.WoWObjects;

namespace WuzzCollection.Helpers
{
    internal static class Safers
    {
        public static void EnsureTarget()
        {
            if(BotSettings.BotTargeting)
            {
                if (StyxWoW.Me.CurrentTarget != null && StyxWoW.Me.CurrentTarget.IsDead)
                {
                    StyxWoW.Me.ClearTarget();
                }

                // If we have a RaF leader, then use its target.
                var rafLeader = RaFHelper.Leader;
                if (rafLeader != null && rafLeader.IsValid && !rafLeader.IsMe && rafLeader.Combat &&
                    rafLeader.CurrentTarget != null && rafLeader.CurrentTarget.IsAlive && !Blacklist.Contains(rafLeader.CurrentTarget))
                {
                    rafLeader.CurrentTarget.Target();
                    return;
                }

                // Check bot poi.
                if (BotPoi.Current.Type == PoiType.Kill)
                {
                    var unit = BotPoi.Current.AsObject as WoWUnit;

                    if (unit != null && unit.IsAlive && !unit.IsMe && !Blacklist.Contains(unit))
                    {
                        unit.Target();
                        return;
                    }
                }

                // Does the target list have anything in it? And is the unit in combat?
                // Make sure we only check target combat, if we're NOT in a BG. (Inside BGs, all targets are valid!!)
                var firstUnit = Targeting.Instance.FirstUnit;
                if (firstUnit != null && firstUnit.IsAlive && !firstUnit.IsMe && firstUnit.Combat &&
                    !Blacklist.Contains(firstUnit))
                {
                    firstUnit.Target();
                    return;
                }

                // Cache this query, since we'll be using it for 2 checks. No need to re-query it.
                var agroMob =
                    ObjectManager.GetObjectsOfType<WoWUnit>(false, false).
                        Where(p => !Blacklist.Contains(p) && p.IsHostile && !p.IsOnTransport && !p.IsDead &&
                                    !p.Mounted && p.DistanceSqr <= 70 * 70 && p.Combat).
                        OrderBy(u => u.DistanceSqr).
                        FirstOrDefault();

                if (agroMob != null)
                {
                    // Return the closest one to us
                    agroMob.Target();
                    return;
                }
            }
        }
    }
}